package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.common.redis.CacheService;
import com.heima.file.service.FileStorageService;
import com.heima.user.config.BaiduConfig;
import com.heima.user.service.ApUserAutoAuditService;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:Dikk
 * @create: 2023-08-05 00:52
 * @Description: ApUserAutoAuditServiceImpl
 */
@Service
@Slf4j
public class ApUserAutoAuditServiceImpl implements ApUserAutoAuditService {

    private static final String URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Autowired
    private CacheService cacheService;

    @Autowired
    private BaiduConfig baiduConfig;

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 身份证图片识别,返回识别结果
     *
     * @return
     */
    @Override
    public Map<String, String> idCard(String imagePath) {

        try {
            byte[] imgData = fileStorageService.downLoadFile(imagePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = cacheService.get("IDCardToken");
            if (accessToken == null) {
                accessToken = obtainToken();
            }

            String result = HttpUtil.post(URL, accessToken, param);

            //返回结果集合
            Map<String, String> resultMap = new HashMap<>();

            Map map = JSON.parseObject(result, Map.class);

            //获取结果
            Integer numberType = (Integer) map.get("idcard_number_type");
            resultMap.put("idcard_number_type", numberType.toString());

            //获取认证用户信息
            Object words_result = map.get("words_result");
            Map dataMap = JSON.parseObject(JSON.toJSONString(words_result), Map.class);

            //获取姓名
            String name = obtainResultMap("姓名", dataMap);
            String nation = obtainResultMap("民族", dataMap);
            String address = obtainResultMap("住址", dataMap);
            String cardNumber = obtainResultMap("公民身份号码", dataMap);
            String birth = obtainResultMap("出生", dataMap);
            String sex = obtainResultMap("性别", dataMap);

            //将数据封装返回
            resultMap.put("name", name);
            resultMap.put("nation", nation);
            resultMap.put("address", address);
            resultMap.put("cardNumber", cardNumber);
            resultMap.put("birth", birth);
            resultMap.put("sex", sex);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取value值
     *
     * @param key
     * @param dataMap
     * @return
     */
    public String obtainResultMap(String key, Map dataMap) {

        Object data = dataMap.get(key);
        Map JSONMap = JSON.parseObject(JSON.toJSONString(data), Map.class);

        String value = JSONMap.get("words").toString();

        return value;
    }


    /**
     * 获取token
     *
     * @return
     */
    public String obtainToken() {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + baiduConfig.getApiKey() +
                            "&client_secret=" + baiduConfig.getApiSecret() + "&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();

            String token = response.body().string();
            token = JSONObject.parseObject(token).getString("access_token");
            cacheService.set("IDCardToken", token);
            return token;
        } catch (IOException e) {
            log.info("token获取失败,失败原因:{}", e);
            return null;
        }
    }
}
